﻿Public Class fMain
    'sets values for operating closing statement timer
    Dim cntdEndMax As Long = 3000
    Dim cntdEndVal As Long = 0

    Private Sub SeznamVýrobkůToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SeznamVýrobkůToolStripMenuItem.Click
        My.Forms.fSetVyrobky.ShowDialog()
    End Sub

    Private Sub EndToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles EndToolStripMenuItem.Click
        'attempts to automatically backup (export) database to NAT external disk
        If Me.chboxZalohovat.Checked = True Then
            Me.lblTStrip1.Text = "Zálohuje se databáze, prosím čekejte...."
            Dim filePath As String = FileIO.FileSystem.CurrentDirectory & "\dtb.accdb"
            Dim savePath As String = "\\192.168.2.4\Carodejka\Backups\Evidence\Dulique_databaze_" _
                                     & Date.Today.Year & "_" & Date.Today.Month & "_" & Date.Today.Day _
                                     & "_" & Date.Now.Hour.ToString & "_" & Date.Now.Minute.ToString & ".accdb"
            Try 'check, if NAT folder is accessible
                If FileIO.FileSystem.DirectoryExists("\\192.168.2.4\Carodejka\Backups\Evidence") = True Then 'if so, then
                    FileIO.FileSystem.CopyFile(filePath, savePath, True) 'copy file to location
                    Me.cntdEnd.Start() 'start timer
                Else
                    MsgBox("Automatická záloha databáze se nepovedla." & vbCrLf _
                       & "Proveďte zálohu přes nabídku 'File\Export databáze'", MsgBoxStyle.Critical, "Chyba!")
                    End
                End If
            Catch ex As Exception
                MsgBox("Automatická záloha databáze se nepovedla." & vbCrLf _
                       & "Proveďte zálohu přes nabídku 'File\Export databáze'", MsgBoxStyle.Critical, "Chyba!")
                End
            End Try
        Else
            End
        End If
    End Sub

    Private Sub SeznamVstupůToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SeznamVstupůToolStripMenuItem.Click
        My.Forms.fSetVstupy.ShowDialog()
    End Sub

    Private Sub ZpůsobProdejeToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ZpůsobProdejeToolStripMenuItem.Click

    End Sub

    Private Sub TypPlatbyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TypPlatbyToolStripMenuItem.Click
        My.Forms.fSetPlatby.ShowDialog()
    End Sub

    Private Sub TypProdejeToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TypProdejeToolStripMenuItem.Click
        My.Forms.fSetProdej.ShowDialog()
    End Sub

    Private Sub btnPříjmy_Click(sender As System.Object, e As System.EventArgs) Handles btnPříjmy.Click
        My.Forms.fZadaniPrijmy.ShowDialog()
    End Sub

    Private Sub fMain_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Me.EndToolStripMenuItem.PerformClick()
    End Sub

    Private Sub fMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'loads needed tabs from dtb
        Me.Tab_kalkulaceTableAdapter.Fill(Me.DtbDataSet1.tab_kalkulace)
        Me.Seznam_vyrobkyTableAdapter.Fill(Me.DtbDataSet1.seznam_vyrobky)
        Me.Tab_prijemTableAdapter1.Fill(Me.DtbDataSet1.tab_prijem)
        Me.Tab_vydajTableAdapter1.Fill(Me.DtbDataSet1.tab_vydaj)
        Me.Seznam_PrijemPostovneTableAdapter1.Fill(Me.DtbDataSet1.seznam_PrijemPostovne)
        'setting of initial values
        Me.MaximizeBox = False
        Me.lblTStrip1.Text = "Připraven."
        Me.lblPrijmyShow.Text = ""
        Me.lblVydajeShow.Text = ""
        Me.lblZiskShow.Text = ""
        Me.lblPostovneShow.Text = ""
        Me.lblZiskBezPostShow.Text = ""
        Me.chboxZalohovat.Checked = My.Settings.chboxZalohovat
        Me.cboxVybratVyrobek.SelectedItem = ""
        Me.cboxVybratVyrobek.SelectedText = ""
        'filling of cbox in tab3
        FillCbox_KalkNaklShow(Me.DtbDataSet1.tab_kalkulace, Me.DtbDataSet1.seznam_vyrobky, Me.cboxZvolitKalkVyrShow)

    End Sub

    Private Sub btnVýdaje_Click(sender As System.Object, e As System.EventArgs) Handles btnVýdaje.Click
        My.Forms.fZadaniVydaje.ShowDialog()
    End Sub

    Private Sub ExportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExportToolStripMenuItem.Click
        'exports database to destination, selected by user
        Dim filePath As String = FileIO.FileSystem.CurrentDirectory & "\dtb.accdb"
        Me.saveF_DtbExport.Filter = "MS Access files (*.accdb)|*.accdb"
        Me.saveF_DtbExport.AutoUpgradeEnabled = True
        Me.saveF_DtbExport.DefaultExt = "*.accdb"
        Me.saveF_DtbExport.OverwritePrompt = True
        Me.saveF_DtbExport.FileName = "Dulique_databaze_" & Date.Today.Year & "_" & Date.Today.Month & "_" & Date.Today.Day _
                                 & "_" & Date.Now.Hour.ToString & "_" & Date.Now.Minute.ToString
        Try
            If Me.saveF_DtbExport.ShowDialog() = Windows.Forms.DialogResult.OK Then
                FileIO.FileSystem.CopyFile(filePath, Me.saveF_DtbExport.FileName.ToString, True)
                Me.lblTStrip1.Text = "Databáze byla úspěšně exportována!"
            Else
                Me.lblTStrip1.Text = "Akce byla zrušena uživatelem."
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba při exportu databáze!")
            Me.lblTStrip1.Text = "Databáze nebyla exportována!"
        End Try
    End Sub

    Private Sub ImportDatabázeToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ImportDatabázeToolStripMenuItem.Click
        'opens dialog to select backup dtb file and saves it into app dir
        Dim filePath As String = FileIO.FileSystem.CurrentDirectory & "\dtb.accdb"
        Dim getDtb As New OpenFileDialog()
        getDtb.InitialDirectory = FileIO.SpecialDirectories.Desktop
        getDtb.AutoUpgradeEnabled = True
        getDtb.DefaultExt = ".accdb"
        getDtb.Filter = "MS Access files (*.accdb)|*.accdb"
        Try
            If getDtb.ShowDialog() = Windows.Forms.DialogResult.OK Then
                FileIO.FileSystem.CopyFile(getDtb.FileName.ToString, filePath, True)
                Me.lblTStrip1.Text = "Databáze byla úspěšně importována!"
            Else
                Me.lblTStrip1.Text = "Akce byla zrušena uživatelem."
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba při importu databáze!")
            Me.lblTStrip1.Text = "Databáze nebyla importována!"
        End Try
    End Sub

    Private Sub cntdEnd_Tick(sender As System.Object, e As System.EventArgs) Handles cntdEnd.Tick
        'shows closing message, if backup was successful, then exit program
        If Me.cntdEndVal < Me.cntdEndMax Then
            Me.lblTStrip1.Text = "Databáze úspěšně zálohována, program se ukončuje..."
            Me.cntdEndVal += 1000
        Else
            End
        End If
    End Sub

    Private Sub TabPage2_Enter(sender As Object, e As System.EventArgs) Handles TabPage2.Enter
        'this code computes total Revenues, Expenses, Postal-fees charged on customer and Profit (with and without Postal-fees)
        'gets needed data from dtb
        Me.Tab_prijemTableAdapter1.Fill(Me.DtbDataSet1.tab_prijem)
        Me.Tab_vydajTableAdapter1.Fill(Me.DtbDataSet1.tab_vydaj)
        Me.Seznam_PrijemPostovneTableAdapter1.Fill(Me.DtbDataSet1.seznam_PrijemPostovne)
        'sets needed vars
        Dim pocRadPrijmy As Long = Me.DtbDataSet1.tab_prijem.Rows.Count()
        Dim pocRadVydaje As Long = Me.DtbDataSet1.tab_vydaj.Rows.Count()
        Dim celkPrijem As Decimal = 0
        Dim celkPostovne As Decimal = 0
        Dim celkVydaj As Decimal = 0
        Dim zisk As Decimal = 0
        Dim arrUniqVal(-1) As Integer
        Dim pocUniqVal As Long = 0
        'get total Income

        If pocRadPrijmy > 0 Then 'if table "tab_prijem" is not blank, then compute and show total Revenues
            Try
                For i As Long = 0 To pocRadPrijmy - 1
                    celkPrijem = celkPrijem + _
                        (Me.DtbDataSet1.tab_prijem.Rows.Item(i).Item(10) * _
                        Me.DtbDataSet1.tab_prijem.Rows.Item(i).Item(11))
                Next i
                Me.lblPrijmyShow.Text = Convert.ToString(celkPrijem)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba při výpočtu celkových příjmů!")
            End Try
            '-----------------------------
            'this code handles computing total Postal-fees sum in four steps:
            '1st step: get total of UNIQUE ids of post-office fees charged on client
            Try
                For i As Long = 0 To pocRadPrijmy - 1
                    Dim polozka As Long = Me.DtbDataSet1.tab_prijem.Rows.Item(i).Item(7)
                    If arrUniqVal.Contains(polozka) = False Then
                        pocUniqVal += 1
                        ReDim Preserve arrUniqVal(pocUniqVal)
                        arrUniqVal(pocUniqVal) = polozka
                    End If
                Next i
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba: Určování počtu unikátních položek poštovného")
            End Try
            '2nd step: get sums of each unique in table "tab_prijem"
            Dim arrUniqValSum(arrUniqVal.GetUpperBound(0)) As Integer
            For i As Long = 0 To arrUniqValSum.GetUpperBound(0)
                For ii As Long = 0 To pocRadPrijmy - 1
                    Dim polozka As Long = Me.DtbDataSet1.tab_prijem.Rows.Item(ii).Item(7)
                    If polozka = arrUniqVal(i) Then
                        arrUniqValSum(i) += 1
                    End If
                Next ii
            Next i
            '3rd step: get values from tab "seznam_PrijemPostovne" accoding to ids stored in arrUniqVal
            Dim arrUniqValProp(arrUniqVal.GetUpperBound(0)) As Decimal
            Dim pocRadkuPostovne As Long = Me.DtbDataSet1.seznam_PrijemPostovne.Rows.Count()
            For i As Long = 0 To arrUniqValProp.GetUpperBound(0)
                For ii As Long = 0 To pocRadkuPostovne - 1
                    Dim radekID As Long = Me.DtbDataSet1.seznam_PrijemPostovne.Rows.Item(ii).Item(0)
                    Dim polozka As Decimal = Me.DtbDataSet1.seznam_PrijemPostovne.Rows.Item(ii).Item(1)
                    If radekID = arrUniqVal(i) Then
                        arrUniqValProp(i) = polozka
                        Continue For
                    End If
                Next ii
            Next i
            '4th step: get total sum of Postovne
            For i As Long = 0 To arrUniqValProp.GetUpperBound(0)
                celkPostovne = celkPostovne + _
                (arrUniqValProp(i) * arrUniqValSum(i))
            Next i
            'displays total Postovne
            Me.lblPostovneShow.Text = Convert.ToString(celkPostovne)
        Else
            Me.lblPrijmyShow.Text = "0"
            Me.lblPostovneShow.Text = "0"
        End If
        '----------------------------
        'get total Expenses
        If pocRadVydaje > 0 Then
            For i As Long = 0 To pocRadVydaje - 1
                celkVydaj = celkVydaj + _
                    (Me.DtbDataSet1.tab_vydaj.Rows.Item(i).Item(9) * _
                    Me.DtbDataSet1.tab_vydaj.Rows.Item(i).Item(10))
            Next i
            Me.lblVydajeShow.Text = Convert.ToString(celkVydaj)
        Else
            Me.lblVydajeShow.Text = "0"
        End If
        'get and show Profit
        If pocRadPrijmy > 0 Then
            Me.lblZiskShow.Text = Convert.ToString( _
                celkPrijem - celkVydaj)
            If (celkPrijem - celkVydaj) > 0 Then
                Me.lblZiskShow.ForeColor = Color.Green
            ElseIf (celkPrijem - celkVydaj) < 0 Then
                Me.lblZiskShow.ForeColor = Color.IndianRed
            Else
                Me.lblZiskShow.ForeColor = Color.Black
            End If
            Me.lblZiskBezPostShow.Text = Convert.ToString( _
                celkPrijem - celkVydaj - celkPostovne)
        Else
            Me.lblZiskShow.ForeColor = Color.Black
            Me.lblZiskShow.Text = "N/A"
            Me.lblZiskBezPostShow.Text = "N/A"
        End If
    End Sub

    Private Sub chboxZalohovat_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chboxZalohovat.CheckedChanged
        If Me.chboxZalohovat.CheckState = CheckState.Checked Then
            My.Settings.chboxZalohovat = True
            My.Settings.Save()
        ElseIf Me.chboxZalohovat.CheckState = CheckState.Unchecked Then
            My.Settings.chboxZalohovat = False
            My.Settings.Save()
        End If
    End Sub

    Private Sub TabPage3_Enter(sender As Object, e As System.EventArgs) Handles TabPage3.Enter


       
    End Sub

    Private Sub cboxVybratVyrobek_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboxVybratVyrobek.SelectedIndexChanged
        My.Forms.fKalkNaklForm.ShowDialog()
    End Sub

    Private Sub btnPrehledyDetail_Click(sender As System.Object, e As System.EventArgs) Handles btnPrehledyDetail.Click
        My.Forms.fPrehledyDetailZobrazeni.ShowDialog()
    End Sub

    Private Sub cboxZvolitKalkVyrShow_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboxZvolitKalkVyrShow.SelectedIndexChanged
        My.Forms.fKalkNaklDetailZobrazeni.ShowDialog()
    End Sub
End Class
